# -*- coding:utf-8 -*-
import sys
import cv2  
import numpy as np 
import pygame
from pygame import gfxdraw
import time
import sys
from pygame.locals import *
from PIL import Image
import tkFileDialog
from tkFileDialog import askdirectory
import tkinter.colorchooser
import shutil

hsv = (0, 0, 0)
cute = not True#True果实剪切按顺序放在图片上方
def get_random(a,b):
    '''得到一个a和b之间的随机数'''
    if a<=b:
        return random.randint(a,b)
    else:
        return random.randint(b,a)
def process_img():
    global apple_number,apple_suface
    global deal_flag
    global r,g,b,h,s,v
    deal_flag = True
    global image_path
    global result_image
    print(image_path)
    print(result_save_as_path)
    im = Image.open(image_path)
    (x,y)=im.size
    fazhi = x/14
    y *= 2
    x *= 2
    out = im.resize((x,y))
    out.save(current_path()+'big_image.jpg')
    Img = cv2.imread(current_path()+'big_image.jpg')
    img_size = Img.shape
    kernel_2 = np.ones((2,2),np.uint8)
    kernel_3 = np.ones((3,3),np.uint8)
    kernel_4 = np.ones((4,4),np.uint8)
    if Img is not None:
        HSV = cv2.cvtColor(Img, cv2.COLOR_BGR2HSV) 
        
        h_low=int((h/2)-4)
        if h_low<0:
            h_low=0
        h_upp=int((h/2)+4)
        if h_upp>360:
            h_upp=360
        Lower = np.array([h_low, 46, 46])  
        Upper = np.array([h_upp, 255, 255])
        print(str(h_low)+'-->'+str(h_upp))  
        mask = cv2.inRange(HSV, Lower, Upper)  
        erosion = cv2.erode(mask,kernel_4,iterations = 1)  
        erosion = cv2.erode(erosion,kernel_4,iterations = 1)  
        dilation = cv2.dilate(erosion,kernel_4,iterations = 1)  
        dilation = cv2.dilate(dilation,kernel_4,iterations = 1)  
        target = cv2.bitwise_and(Img, Img, mask=dilation)  
        ret, binary = cv2.threshold(dilation,127,255,cv2.THRESH_BINARY)     
        contours, hierarchy = cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)    
        p=0
        r=0
        l=0
        roi_max_hight =0
        for i in contours:
            x,y,w,h = cv2.boundingRect(i)
            if h>fazhi and w>fazhi:
                if cute:
                    apple=Img[y:y+h,x:x+w]
                    try:
                        Img[l:l+h,r:r+w]=apple
                    except:
                        pass
                    r = r+w+1
                    if roi_max_hight<h:
                        roi_max_hight=h
                    if r+300>img_size[1]:
                        r=0
                        l=roi_max_hight  
                cv2.rectangle(Img,(x,y),(x+w,y+h),(20,20,255),20)   
                p +=1
        apple_number = p
        print 'apple number ',p
        cv2.imwrite(current_path()+'result.jpg',Img)
        
def save_img():
    global result_save_as_path
    try:
        result_save_as_path = askdirectory()
        path = result_save_as_path+'/result.jpg'
        print(path)
        shutil.copy(current_path()+'result.jpg',path)
    except:
        pass
    
def get_img():
    global image_path
    image_path = tkFileDialog.askopenfilename()

def get_preview_show_image(image):
    global image_size_x ,image_size_y, preview_image_size_x, preview_image_size_y
    try:
        im = Image.open(image)
        (x,y)=im.size
        image_size_x ,image_size_y = (x,y)
        if x>y:
            width=630
            y = int(y*width/x)
            x = width
            preview_image_size_x = x
            preview_image_size_y = y
            out = im.resize((x,y))
            out.save(current_path()+'preview_image.jpg')
        else:
            height = 600
            x = int(x*height/y)
            y = height
            preview_image_size_x = x
            preview_image_size_y = y
            out = im.resize((x,y))
            out.save('preview_image.jpg')
    except:
        print('tu pian jia zai shi bai')

def get_result_show_image(image):
    try:
        im = Image.open(image)
        (x,y)=im.size
        if x>y:
            width=345
            y = int(y*width/x)
            x = width
            out = im.resize((x,y))
            out.save(current_path()+'result_image.jpg')
        else:
            height = 330
            x = int(x*height/y)
            y = height
            out = im.resize((x,y))
            out.save(current_path()+'result_image.jpg')
    except:
        print('tupianjiazaishibai')
def choose_color():
    '''颜色选择函数，返回颜色元组'''
    return tkinter.colorchooser.askcolor()[0]
def select_apple_color(surface):
    global r,g,b,h,s,v, show_r, show_g, show_b
    x, y = pygame.mouse.get_pos()
    r, g, b = surface.get_at((x-50, y-110))[0:3]
    print(r, g, b)
    show_r, show_g, show_b = r,g,b
    r, g, b = r/255.0, g/255.0, b/255.0
    mx = max(r, g, b)
    mn = min(r, g, b)
    df = mx-mn
    if mx == mn:
        h = 0
    elif mx == r:
        h = (60 * ((g-b)/df) + 360) % 360
    elif mx == g:
        h = (60 * ((b-r)/df) + 120) % 360
    elif mx == b:
        h = (60 * ((r-g)/df) + 240) % 360
    if mx == 0:
        s = 0
    else:
        s = df/mx
    v = mx
    
    #hsv = h, s, v
    if test:
        print('hsv ->'+str(h/2)+str(s*255)+str(v*255))
def draw_shape(tuopu):
    pass#画拓扑图
    if test:
        print(tuopu)
    x = []
    y = []
    x1 = []
    x2 = []
    x3 = []
    x4 = []
    for i in tuopu:
        x.append(i[0])
        y.append(i[1])
    max_x = max(x)
    min_x = min(x)
    max_y = max(y)
    min_y = min(y)
    for i in range(len(x)):
        x[i] = int((x[i]-min_x)*220/(max_x-min_x))
    if test:
        print('x')
        print(x)
    for i in range(len(y)):
        y[i] = int((y[i]-min_y)*220/(max_y-min_y))
    for i in range(len(y)):
        if y[i] == 0:
            top_x, top_y = x[i],0
        if y[i] > 219:
            low_x, low_y = x[i],220
        if 40<y[i]<60:
            x1.append(x[i])
        if 90<y[i]<110:
            x2.append(x[i])
        if 140<y[i]<160:
            x3.append(x[i])
        if 190<y[i]<210:
            x4.append(x[i])
    x1_max =max(x1)
    x1_min =min(x1)
    x2_max =max(x2)
    x2_min =min(x2)
    x3_max =max(x3)
    x3_min =min(x3)
    x4_max =max(x4)
    x4_min =min(x4)
    pygame.draw.circle(screen,[255,0,0],[top_x+970,top_y+90],4,0)
    pygame.draw.circle(screen,[255,0,0],[low_x+970,230+90],4,0)
    pygame.draw.circle(screen,[255,0,0],[x1_max+970,50+90],4,0)
    pygame.draw.circle(screen,[255,0,0],[x1_min+970,50+90],4,0)
    pygame.draw.circle(screen,[255,0,0],[x2_max+970,100+90],4,0)
    pygame.draw.circle(screen,[255,0,0],[x2_min+970,100+90],4,0)
    pygame.draw.circle(screen,[255,0,0],[x3_max+970,150+90],4,0)
    pygame.draw.circle(screen,[255,0,0],[x3_min+970,150+90],4,0)
    pygame.draw.circle(screen,[255,0,0],[x4_max+970,200+90],4,0)
    pygame.draw.circle(screen,[255,0,0],[x4_min+970,200+90],4,0)
    #pygame.draw.line(screen,color,(100,100),(500,400),width)
    pygame.draw.line(screen,[255,0,0],[top_x+970,top_y+90],[x1_max+970,50+90],2)
    
    pygame.draw.line(screen,[255,0,0],[x1_max+970,50+90],[x2_max+970,100+90],2)
    pygame.draw.line(screen,[255,0,0],[x2_max+970,100+90],[x3_max+970,150+90],2)
    pygame.draw.line(screen,[255,0,0],[x3_max+970,150+90],[x4_max+970,200+90],2)
    pygame.draw.line(screen,[255,0,0],[x4_max+970,200+90],[low_x+970,230+90],2)
    
    pygame.draw.line(screen,[255,0,0],[top_x+970,top_y+90],[x1_min+970,50+90],2)
    
    pygame.draw.line(screen,[255,0,0],[x1_min+970,50+90],[x2_min+970,100+90],2)
    pygame.draw.line(screen,[255,0,0],[x2_min+970,100+90],[x3_min+970,150+90],2)
    pygame.draw.line(screen,[255,0,0],[x3_min+970,150+90],[x4_min+970,200+90],2)
    pygame.draw.line(screen,[255,0,0],[x4_min+970,200+90],[low_x+970,230+90],2)


    
def current_path():
    path = str(sys.path[0])+'\\'
    return path
def get_resolution():
    return pygame.display.list_modes()[0]
test = True#True测试模式,not True不测试
set_preview_image_position = 50,110#（x, y）
set_result_image_position = 770,380
set_apple_suface_position = 1235,415#苹果数量位置
set_apple_color_position = 1222,630#RGB值位置
set_size_x_position = 1235,484#宽度位置
set_size_y_position = 1235,557#高度位置
image_path = 'tree.jpg'
result_path = 'result.jpg'
preview_image_file = 'preview_image.jpg'
result_image_file= 'result_image.jpg'
result_save_as_path = None
deal_flag = not True
cute_flag = not True
cute_color = (255,255,255)
font_color = (39,216,251)
apple_number = 0
r, g, b = 0, 0, 0
h, s, v = 0, 0, 0
show_r, show_g, show_b = 0, 0, 0
image_size_x ,image_size_y = 0,0
preview_image_size_x, preview_image_size_y = 0, 0

pygame.init()
font = pygame.font.Font(None, 45)
apple_suface = font.render(str(apple_number),True,font_color)
color = pygame.font.Font(None, 30)
apple_color = color.render('('+str(r)+','+str(g)+','+str(b)+')',True,font_color)

size_xx = pygame.font.Font(None, 45)
size_x = size_xx.render(str(image_size_x),True,font_color)
size_yy = pygame.font.Font(None, 45)
size_y = size_yy.render(str(image_size_y),True,font_color)
if test:
    qqqq = pygame.font.Font(None, 40)
    qqq = qqqq.render('('+str(0)+str(0)+')',True,font_color)

clock = pygame.time.Clock()
width, height = get_resolution()
width, height = width-20, height-100
screen = pygame.display.set_mode(get_resolution())#(width, height), FULLSCREEN | HWSURFACE
pygame.display.set_caption('果实信息提取器')

background = pygame.image.load('整体软件背景.png').convert()#current_path()+

get_preview_show_image(image_path)
preview_image = pygame.image.load(preview_image_file)
preview_image_position = preview_image.get_rect()
preview_image_position = set_preview_image_position

get_result_show_image(result_path)
result_image = pygame.image.load(result_image_file)
result_image_position = result_image.get_rect()
result_image_position = set_result_image_position

image_path_copy = image_path
print(image_path)
draw_xy =[]
draw_x = []
draw_y = []
screen.blit(background, (0, 0))
clock.tick(20)
while True:
    for event in pygame.event.get():
        #print(str(event)+'\n')
        if event.type == QUIT:
            sys.exit()
        if event.type == MOUSEMOTION:
            if test:
                x, y = pygame.mouse.get_pos()
                qqq = color.render('('+str(x)+','+str(y)+')',True,font_color)
        if event.type == MOUSEBUTTONDOWN:
            x, y = pygame.mouse.get_pos()
            if 460<x<620 and 23<y<55:
                get_img()
            if 50<x<(40+preview_image_size_x) and 110<y<(313+preview_image_size_y):
                select_apple_color(preview_image)
                apple_color = color.render('('+str(show_r)+','+str(show_g)+','+str(show_b)+')',True,font_color)
                
            if 635<x<790 and 23<y<55:
                process_img()
            if 1000<x<1160 and 23<y<55:#颜色选择
                cute_color = choose_color()
            if 820<x<980 and 23<y<55:
                save_img()
            if 1180<x<1350 and 23<y<55:
                sys.exit()
            print('x ->'+str(x))
            print('y ->'+str(y))
        if event.type == pygame.MOUSEMOTION and event.buttons == (0,0,1):#画轮廓
            xy = event.pos
            gfxdraw.pixel(screen,xy[0],xy[1],  cute_color)
            gfxdraw.pixel(screen,xy[0]+1,xy[1],cute_color)
            gfxdraw.pixel(screen,xy[0]-1,xy[1],cute_color)
            gfxdraw.pixel(screen,xy[0],xy[1]+1,cute_color)
            gfxdraw.pixel(screen,xy[0],xy[1]-1,cute_color)
            draw_xy.append(xy)
            draw_x.append(xy[0])
            draw_y.append(xy[1])
            cute_flag = True
        if event.type == MOUSEBUTTONUP and cute_flag:
            try:
                preview_image_cv2 = cv2.imread(preview_image_file)
                cute_image = preview_image_cv2[min(draw_y)-110:max(draw_y)-110,min(draw_x)-50:max(draw_x)-50]#裁剪图片
                cv2.imwrite('cute_image.jpg',cute_image)
                time.sleep(0.1)
                image_path = 'cute_image.jpg'
                if test:
                    pass
                    #print('max draw_x',max(draw_x))
                    #print('min draw_x',min(draw_x))
                    #print('max draw_y',max(draw_y))
                    #print('min draw_y',min(draw_y))
                cute_flag = not True
                draw_shape(draw_xy)
                draw_x = []
                draw_y = []
            except:
                print('!!!!!!')
        if event.type == KEYDOWN:
            if event.key == K_q:
                sys.exit()
            if event.key == K_LEFT:
                pass
            if event.key == K_RIGHT:
                pass
            if event.key == K_UP:
                pass
            if event.key == K_DOWN:
                pass

    if image_path_copy != image_path:
        print('file changed')
        image_path_copy = image_path
        get_preview_show_image(image_path)
        preview_image = pygame.image.load(preview_image_file)
        preview_image_position = preview_image.get_rect()
        preview_image_position = set_preview_image_position
        pygame.draw.rect(screen, (15,24,32),[50, 110, 630, 600])
        screen.blit(preview_image, preview_image_position)
    if deal_flag:
        deal_flag = not True
        get_result_show_image(result_path)
        result_image = pygame.image.load(result_image_file)
        result_image_position = result_image.get_rect()
        result_image_position = set_result_image_position

        apple_suface = font.render(str(apple_number),True,font_color)
        apple_suface_position = apple_suface.get_rect()
        apple_suface_position.center = set_apple_suface_position

        size_x = size_xx.render(str(image_size_x),True,font_color)
        size_x_position = size_x.get_rect()
        size_x_position.center = set_size_x_position

        size_y = size_yy.render(str(image_size_y),True,font_color)
        size_y_position = size_y.get_rect()
        size_y_position.center = set_size_y_position
        
        pygame.draw.rect(screen, (15,24,32),[770, 380, 345, 300])#清除结果栏信息
        screen.blit(result_image, result_image_position)        
        
    if test:
        pygame.draw.rect(screen, (255,255,255),[0, 0, 100, 25])
        screen.blit(qqq, (0,0))
    
    pass#清除数字显示信息
    pygame.draw.rect(screen, (15,24,32),[1235, 415, 60, 25])#苹果数量位置清除数字显示信息
    pygame.draw.rect(screen, (15,24,32),[1235, 484, 75, 25])#宽度位置清除数字显示信息
    pygame.draw.rect(screen, (15,24,32),[1235, 557, 75, 25])#高度位置清除数字显示信息
    pygame.draw.rect(screen, (15,24,32),[1222, 630, 135, 25])#RGB值位置清除数字显示信息

    screen.blit(apple_suface, set_apple_suface_position)
    screen.blit(size_x, set_size_x_position)
    screen.blit(size_y, set_size_y_position)
    screen.blit(apple_color, set_apple_color_position)
    pygame.draw.rect(screen, (show_r,show_g,show_b),[763, 87, 35, 230])
    pygame.display.flip()
    clock.tick(20)
